<?php

class RegController extends CustomControllerAction
{
	public function init()
	{
		parent::init();
	}
	
	public function signupAction()
	{
		$this->logger->debug('signupAction entered');
		
		$user = array();
		$user['name'] 		= array('label'=>'Name');
		$user['password'] 	= array('label'=>'Password', 'type'=>'password');
		$user['confirm'] 	= array('label'=>'Confirm', 'type'=>'password');
		$user['email'] 		= array('label'=>'E-mail');
		$user['birthday'] 	= array('label'=>'Birthday');
		$user['captcha'] 	= array('label'=>'Enter the code'); 
		
		if ($this->getRequest()->isPost())
		{
			try 
			{
				{ // user fields
					$request = $this->getRequest();
					$user['name']['value'] 		= htmlspecialchars(trim(  $request->getParam('name')  ));
			        $user['password']['value'] 	= htmlspecialchars(  $request->getParam('password')  );
			        $user['confirm']['value']	= htmlspecialchars(  $request->getParam('confirm')  );
			        $user['email']['value'] 	= htmlspecialchars(trim(  $request->getParam('email')  ));
			        $user['birthday']['value'] 	= htmlspecialchars(trim(  $request->getParam('birthday')  ));
			        $user['captcha']['value'] 	= htmlspecialchars(trim(strtolower(  $request->getParam('captcha')  )));
				}
		        
		        { // validating
		            $captcha_session = new Zend_Session_Namespace('captcha');
		            
			        $user['name']['validator'] 		= new Zend_Validate_Regex(array('pattern'=>'/^[a-zA-Z0-9\-_]{3,20}$/'));
			        $user['password']['validator'] 	= new Zend_Validate_StringLength(array('min'=>5, 'max'=>100));
			        $user['confirm']['validator'] 	= new Zend_Validate_Identical(array('token'=>$user['password']['value']));
			        $user['email']['validator']		= new EmailValidator();
			        $user['birthday']['validator'] 	= new Zend_Validate_Date(array('format'=>'dd MMMM yyyy', 'locale'=>'en'));
			        $user['captcha']['validator'] 	= new Zend_Validate_Identical(array('token'=>$captcha_session->code));
		        
		        	$ok = true;
					foreach ($user as $key => $field)
					{
						if (  !$field['validator']->isValid($field['value'])  ) {
			        		$ok = false;
			        		foreach ($field['validator']->getMessages() as $msg)
			        			$user[$key]['error'] = $msg;
			        	}
					}
					if (!$ok)
						throw new Exception('Validating failed. ');
		        }
		        
		        { // storing
		        	$ut = new UsersTable();
	        		$ut->AddUser(
	        				$user['name']['value'], 
	        				$user['password']['value'], 
	        				$user['email']['value'], 
	        				$user['birthday']['value']);
		        }
		        
		        { // cleaning up
		        //TODO how to clear values ??
		        	$user['name']['value'] = '';
		        	$user['password']['value'] = '';
		        	$user['confirm']['value'] = '';
		        	$user['email']['value'] = '';
		        	$user['birthday']['value'] = '';
		        	$user['captcha']['value'] = '';
		        }
		        $this->view->added = true;
			}
			catch (Exception $ex)
			{
				$this->view->failed = true;
				$user['captcha']['value'] = '';
				$this->logger->err($ex);
			}
		}
		
		
		$this->view->user = $user;
		
		$this->logger->debug('signupAction finished');
	}
	
	
	public function usersAction()
	{
		try
		{
			$request = $this->getRequest();
			$sort_by = htmlspecialchars(trim(  $request->getParam('sort_by')  ));
			$validator = new Zend_Validate_InArray(  array('haystack'=>array('name', 'create_date'))  );
			if (!$validator->isValid($sort_by))
				$sort_by = 'name';
				
			$users_table = new UsersTable();
			$this->view->users = $users_table->getAllUsers($sort_by);
		}
		catch (Exception $ex)
		{
			$this->view->error = "We are sorry! User list is not available now.";
			$this->logger->err("Retrieving users failed. {$ex}");
		}
	}
	
	public function phpinfoAction()
	{
		$this->_helper->viewRenderer->setNoRender();
		echo phpinfo();
	}
	
	public function captchaAction()
	{
		$this->logger->debug('captchaAction started');
		
		$captcha_config = Zend_Registry::get('captcha_config');
		$width = $captcha_config->params->width;  //Ширина изображения
        $height = $captcha_config->params->height;  //Высота изображения
		$font_size = $captcha_config->params->font_size;  //Размер шрифта
        $count_letters = $captcha_config->params->letters;  //Количество символов, которые нужно набрать
		//Количество символов, которые находятся на фоне
        $bg_letters = $captcha_config->params->bg_letters;
        $path_fonts = $captcha_config->paths->fonts;  //Путь к шрифтам
        
        
        $letters = array('a','b','c','d','e','f','g','h','j','k','m','n','p','q','r','s','t','u','v','w','x','y','z','2','3','4','5','6','7','9');
        $colors = array('10','30','50','70','90','110','130','150','170','190','210', '230', '250');

        $src = imagecreatetruecolor($width, $height);
        
        $bkg = imagecolorallocate($src, 255, 255, 255);
        imagefill($src, 0, 0, $bkg);
        
        $fonts = array();
        $dir = opendir($path_fonts);
        while($fontName = readdir($dir))
        {
        	if($fontName != "." && $fontName != "..") {
            	$fonts[] = $fontName;
            }
        }
        
        
        closedir($dir);                                             

        for($i = 0; $i < $bg_letters; $i++)
        {
        	$color = imageColorAllocateAlpha($src, rand(0,255), rand(0,255), rand(0,255), 95);
            $font = $path_fonts . '/' . $fonts[rand(0, sizeof($fonts) - 1)];
            $letter = $letters[rand(0, sizeof($letters) - 1)];
            $size = rand($font_size + 8, $font_size);

            imageTtfText($src, $size, rand(0,45),
            	rand($width * 0.1, $width - $width * 0.1),
				rand($height * 0.2, $height),
            	$color, $font, $letter);
        }

        for($i = 0; $i < $count_letters; $i++)
        {
        	$color = imageColorAllocateAlpha($src, $colors[rand(0, sizeof($colors) - 1)],
            		$colors[rand(0, sizeof($colors) - 1)],
					$colors[rand(0, sizeof($colors) - 1)],
                    rand(20, 40));

            $font = $path_fonts . '/' . $fonts[rand(0, sizeof($fonts) - 1)];
            $letter = $letters[rand(0, sizeof($letters) - 1)];
            $size = rand($font_size * 2.1 - 2, $font_size * 2.1 + 2);
            $x = ($i + 1) * $font_size + rand(4, 7);
            $y = (($height * 2) / 3) + rand(0, 5);
            $code[] = $letter;

            imageTtfText($src, $size, rand(0, 30), $x, $y, $color, $font, $letter);
        }

        $captcha_session = new Zend_Session_Namespace('captcha');
        $captcha_session->code = implode('', $code);
        $this->logger->debug("captcha: $captcha_session->code"); 
        
		$this->_helper->viewRenderer->setNoRender();
		
        header("Content-type: image/gif");
        echo imagegif($src);
        
        $this->logger->debug('captchaAction finished');
	}
	
	public function loginAction()
	{
		$this->logger->debug('loginAction entered');
		
		$user = array();
		$user['name'] 		= array('label'=>'Name');
		$user['password'] 	= array('label'=>'Password', 'type'=>'password');
		
		if ($this->getRequest()->isPost())
		{
			$this->logger->debug('post request');
			try 
			{
				{ // user fields
					$request = $this->getRequest();
					$user['name']['value'] 		= htmlspecialchars(trim(  $request->getParam('name')  ));
			        $user['password']['value'] 	= htmlspecialchars(  $request->getParam('password')  );
			    }
		        
		        { // validating
		            $users_table = new UsersTable();
		            $user_row = $users_table->getUserByName($user['name']['value']);
		            
		            $ok = true;
		            
		            if ($user_row == null)
		            {
		            	$user['name']['error'] = 'User hasn\'t been found';
		            	$ok = false;
		            }
		            else if ($user_row['password'] != $user['password']['value'])
		            {
		            	$user['password']['error'] = 'Password is wrong';
		            	$ok = false;
		            }
			        if (!$ok)
						throw new Exception('Logging in failed. ');
		        }
		        
		        $user_session = new Zend_Session_Namespace('user');
        		$user_session->loggedin = true;
        		$user_session->name = $user['name']['value'];
			}
			catch (Exception $ex)
			{
				$this->logger->err($ex);
			}
		}
		
		$this->view->user = $user;
		$user_session = new Zend_Session_Namespace('user');
        $this->view->loggedin = $user_session->loggedin;
        $this->view->name = $user_session->name;
		
		if ($this->getRequest()->isXmlHttpRequest())
		{
			$this->logger->debug('ajax request');
			$data = array();
			$data['user'] = $user;
			$data['loggedin'] = $this->view->loggedin;
			$this->sendJson($data);
		}
		
		$this->logger->debug('loginAction finished');
		
	}
	
	public function logoutAction()
	{
		$this->_helper->viewRenderer->setNoRender();
		$user_session = new Zend_Session_Namespace('user');
        $user_session->loggedin = false;
        $this->_redirect("/reg/login");
	}
	
	/*public function loginAjaxAction()
	{
		$request = $this->getRequest();
		
		// проверяем, является ли запрос - ajax-запросом
		if ($request->isXmlHttpRequest())
		{
	    	// производим некоторые манипуляции
			$id = $request->getPost('id');
			
			$response = $this->getResponse();
			$response->setBody("iehaa");
			
			$this->logger->debug("ajax = " . $id);
		}
	
		$this->_helper->viewRenderer->setNoRender();
	}*/
	
}

?>
